-module(mochiweb_simple_post).

-include_lib("../include/ewgi_unit.hrl").
-include("../../include/ewgi.hrl").

-export([loop/1, handle_req/1]).

-define(PORT, 8000).

-define(DEFAULTS, [{name, ?MODULE},
                   {port, ?PORT}]).

-define(RESPONSE, <<"It's working!">>).
-define(CONTENT_TYPE, "application/x-www-form-urlencoded").
-define(DATA, "foo=bar&bar=baz").

%%--------------------
%% Tests
%%--------------------
%% Setup Tests
setup_test() ->
    try
        application:start(inets),
        {ok, _Pid} = mochiweb_http:start([{loop, fun ?MODULE:loop/1} | ?DEFAULTS])
    catch
	Err:Reason ->
            error_logger:error_report({Err, Reason}),
	    error
    end.

loop(Req) ->
    M = ewgi_mochiweb:new(fun ?MODULE:handle_req/1),
    M:run(Req).

handle_req(Ctx) ->
    {ewgi_context, Req, _Resp} = Ctx,
    ?eq(ewgi_api:server_software(Ctx), "MochiWeb"),
    ?eq(ewgi_api:server_name(Ctx), "localhost"),
    ?eq(ewgi_api:gateway_interface(Ctx),"EWGI/1.0"),
    ?eq(ewgi_api:server_protocol(Ctx), "HTTP/1.1"),
    ?eq(ewgi_api:server_port(Ctx), 8000),
    ?eq(ewgi_api:request_method(Ctx), 'POST'),
    ?eq(ewgi_api:path_info(Ctx), "/"),
    ?eq(ewgi_api:path_translated(Ctx), undefined),
    ?eq(ewgi_api:script_name(Ctx), ""),
    % same hanlder for 2 GET requests.
    % one has a query string and one hasn't
    % check for both
    ?eq(ewgi_api:query_string(Ctx),""),
    ?eq(ewgi_api:content_type(Ctx), ?CONTENT_TYPE),
    ?eq(ewgi_api:content_length(Ctx), length(?DATA)),
    Headers = [{"accept", undefined}, 
               {"cookie", undefined}, 
               {"host", "localhost"}, 
               {"if-modified-since", undefined},
               {"user-agent", undefined},
               {"x-http-method-override", undefined},
               {"Te", []},
               {'Connection', "keep-alive"}],
    ?eq(ewgi_api:get_all_headers(Ctx), Headers),
    ?eq(ewgi_api:remote_host(Ctx), undefined),
    ?eq(ewgi_api:remote_addr(Ctx), "127.0.0.1"),
    ?eq(ewgi_api:auth_type(Ctx), undefined),
    ?eq(ewgi_api:remote_user(Ctx), undefined),
    ?eq(ewgi_api:remote_ident(Ctx),undefined),
    ?eq(ewgi_api:url_scheme(Ctx), "http"),
    ?eq(ewgi_api:version(Ctx), {1, 0}),
    ?eq(ewgi_api:get_all_data(Ctx), gb_trees:empty()),
    {ewgi_context, Req, #ewgi_response{status=?OK, headers=[], message_body=?RESPONSE}}.

test_simple_post() ->
    {ok, Result} = http:request(post, {"http://localhost:8000/", 
                                       [], 
                                       "application/x-www-form-urlencoded", 
                                       "foo=bar&bar=baz"}, [], []),
    {Proto, _Headers, Body} = Result,
    [?eq(Proto, {"HTTP/1.1", 200, "OK"}),
     ?eq(Body, binary_to_list(?RESPONSE))].

%%--------------------
%% Internal Functions
%%--------------------

end_test() ->
    mochiweb_http:stop(?MODULE).

